package com.neuedu.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * http://localhost:8080/web06/download?fileName=2966de9b0dbb4222825d94fbae643628.png
 * http://localhost:8080/web06/download?fileName=4123c45601f04c28ad1330309d932b11.png
 * http://localhost:8080/web06/download?fileName=package.png
 *
 *
 * http://localhost:8080/web06/download?id=5
 */
@WebServlet(value = "/download")
public class DownloadServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }


    //png   gif  jpg  doc  docx ppt
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收一个文件名
        String fileName = req.getParameter("fileName");
        String id = req.getParameter("id");

        //通过id -- dao  ---》  getByID  UploadFile--getFileName


        String path  =FileUploadServlet.UPLOAD_DIR+fileName;
//        执行下载的动作
        resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("下载.png","utf-8") +"");
        resp.setContentType("image/png");
        File File = new File(path);

        FileInputStream inputStream  = new FileInputStream(File);
        OutputStream os = resp.getOutputStream();

        byte buffer[] = new byte[1024];
        int  len = -1;
        while ( ( len =inputStream.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        os.flush();
        os.close();
        inputStream.close();





    }
}
